package stone.ast;

import org.jetbrains.annotations.NotNull;
import runner.Environment;

import java.util.List;

import static runner.Environment.FALSE;

public class WhileStmt extends ASTList {
  public WhileStmt(List<ASTree> list) {
    super(list);
  }

  @Override
  public String toString() {
    return "(while " + condition() + " " + body() + ")";
  }

  public ASTree body() {
    return child(1);
  }

  public ASTree condition() {
    return child(0);
  }

  @NotNull
  @Override
  public Object eval(Environment env) {
    Object result = 0;
    for (; ; ) {
      Object c = condition().eval(env);
      if (c instanceof Integer && (Integer) c == FALSE)
        return result;
      else
        result = body().eval(env);
    }
  }
}
